package com.imyours.net.messagedisposer;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.imyours.net.exception.ErrorCodeException;
import com.imyours.net.exception.ShowException;
import com.imyours.net.result.ExecuteResult;

/**
 * 消息处理父类
 * 
 * @author SLevenc
 * 
 */
public abstract class MessageDisposer {

	public MessageDisposer(ExecuteResult result, String text) {
		this.result = result;
		try {
			JSONObject jo = parseJson(text);
			if (jo.getString("state").equalsIgnoreCase("success")) {
				execute(jo.getJSONObject("data"));
			} else {
				JSONArray errors = jo.getJSONArray("error");
				for (int i = 0; i < errors.size(); i++) {
					result.addThrowAble(new ErrorCodeException(Integer.parseInt(errors.getJSONObject(i).getString(
							"code"))));
				}
			}
		} catch (Throwable t) {
			result.getExceptions().add(t);
		}
	}

	protected ExecuteResult result = null;

	protected JSONObject parseJson(String text) throws Exception {
		JSONObject jo;
		try {
			jo = JSONObject.fromObject(text);
		} catch (Exception ex) {
			result.addThrowAble(new ShowException("数据格式错误"));
			throw ex;
		}

		return jo;

	}

	/**
	 * 解析文本的具体实现
	 * 
	 * @param text
	 */
	protected abstract void execute(JSONObject jo) throws Throwable;

	public ExecuteResult getResult() {
		return result;
	}

	public void setResult(ExecuteResult result) {
		this.result = result;
	}

}
